package org.redswallow.filter.plugin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.redswallow.filter.Constants;
import org.redswallow.log.LogFactory;
import org.redswallow.util.Utils;
import org.redswallow.util.config.ConfigConstants;
import org.redswallow.util.config.IPropertySet;
import org.slf4j.Logger;

public class ForbiddenWordPlugin extends AbstractParameterCheckPlugin implements Plugin {

	public static final String MODULE_NAME = "Special Word Forbidden Plugin";
    public static final String MODULE_VERSION = "v1.0";
    public static final String MODULE_DESCRIPTION = "Special Words find and Forbidden.";
	
    public static final String CONFIG_FORBIDDEN_MSG = "forbiddenmessage";
    
    private final Collection<Pattern> forbiddenWords;
    
    private Logger log = LogFactory.getLog(ForbiddenWordPlugin.class);
    
    public ForbiddenWordPlugin(IPropertySet config) { 
    	
    	super(config);
    	
    	//加载禁止关键字参数
    	int count = config.getInteger(ConfigConstants.CONFIG_COUNT, 0);
    	    	
    	List<Pattern> patterns = new ArrayList<Pattern>(5);
    	for(int i=0; i<count; ++i) {
    		String words = config.getString(""+(i+1), null);
    		if (Utils.isNonBlank(words)) {
    			log.debug("load words:{}", words);
    			patterns.add(Pattern.compile(words));
    		}
    	}
    	forbiddenWords = Collections.unmodifiableList(patterns);
    	
    }
    
    @Override
	public String getDescription() {
		return MODULE_DESCRIPTION;
	}
    
	@Override
	public String getName() {
		return MODULE_NAME;
	}
	
	@Override
	public String getVendor() {
		return Constants.VENDOR;
	}
	
	@Override
	public String getVersion() {
		return MODULE_VERSION;
	}
	
	@Override
	public void initialize() {
	}
	
	@Override
	public void shutdown() {
	}

	@Override
	protected boolean checkParam(String name, Map<String, String[]> map,
			ServletResponse response) {
		
		String[] values = map.get(name);
		
		for(String value : values) {
			for(Pattern regex : forbiddenWords) {
				if (regex.matcher(value).find()) {
					
					if (response instanceof HttpServletResponse) {
						HttpServletResponse hres = (HttpServletResponse) response;
						try {
							hres.sendError(HttpServletResponse.SC_FORBIDDEN);
						} catch (IOException e) {
							log.error("Http send error fail.", e);
						}
					}
					
					return false;
				}
			}
		}
		
		//检查通过
		return true;
	}
    
	
}
